#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include "UdpServer.hpp"
#include <memory>
#include "commd.hpp"
using namespace std;

string func(string s) {
    return "I get you: " + s;
}

// 执行程序替换
string ExecuteCommand(string command) {
    cout << "get a command: " << command << endl;
    FILE* fp = popen(command.c_str(), "r");
    if (fp == nullptr) {
        cout << "execute err reason unknown" << endl;
        exit(-1);
    }

    // 读取结果
    string response;
    char buffer[1024];
    while (true) {
        char* s = fgets(buffer, sizeof buffer, fp);
        if (!s) {
            break;
        } else {
            response += buffer;
        }
    }

    pclose(fp);
    return response.empty() ? "success" : response;
}

void Usage(string proc) { // 使用手册
    cout << "Usage: \n\t" << proc << " local_port\n" << endl;
}

int main(int argc, char* args[]) {
    if (argc != 2) {
        Usage(args[0]);
        return Usage_Erro;
    }
    uint16_t port = atoi(args[1]);
    // unique_ptr<UdpServer> up = unique_ptr<UdpServer>(UdpServer(ip, port));
    UdpServer* up = new UdpServer(ExecuteCommand, port);
    up->Init();
    up->Start();


    return 0;
}